package com.PGD.model.managers
{
	import com.PGD.model.vos.ISlidePack;
	import com.PGD.model.vos.Slide;
	
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	
	import mx.collections.ArrayCollection;
	
	import uranrus.persistence.*;
	
	public class SlidePackManager extends BazManager
	{
		/**
		 *At this point top level is not using a bazManaged collection - reason: as slide packs may not be added or removed 
		 */		
		private var dispatcher:IEventDispatcher;
		private var slidePackPersistenceInfo:PersistenceDescription;
		private var answerSetPersistenceInfo:PersistenceDescription;
		private var commandPackFactory:DataStoreCommandPackFactory;
		
		
		
		public function SlidePackManager(disp:IEventDispatcher = null)
		{
			dispatcher = disp;
		}
		
		private var _selectedSlidePack:ISlidePack;
		[Bindable(event="slidePacksChange")]
		public function get selectedSlidePack ():ISlidePack
		{
			return _selectedSlidePack;
		}
		private var _slidePacks:ArrayCollection;
		public function setSlidePacks (value:ArrayCollection):void
		{
			//this app currently only using one slide pack
			setItems(value);
			if(value && value.length>0)
			{
				_selectedSlidePack = value.getItemAt(0) as ISlidePack;
				dispatchEvent(new Event("slidePacksChange"));
			}
			
		}
		
		override public function save():void
		{
			
			var commandPacks:ArrayCollection = new ArrayCollection;
			if(selectedSlidePack)
			{
				if(selectedSlidePack.needToPersist)
				{
					for each(var slide:Slide in selectedSlidePack.slides)
					{
						if(slide.isNew && !slide.isDeleted)
						{
							commandPacks.addItem(makeUpdateCommands(slide, "Slide", DataStoreCommand.INSERT));
						}
						else if(slide.isDirty)
						{
							commandPacks.addItem(makeUpdateCommands(slide, "Slide", DataStoreCommand.UPDATE));
						}
						
					}
					var slides:BazManagedCollection = selectedSlidePack.slides as BazManagedCollection;
					for each(var slideToDelete:Slide in slides.removedItems)
					{
						commandPacks.addItem(makeUpdateCommands(slide, "Slide", DataStoreCommand.DELETE));
					}	
				}
			}
			
			trace(commandPacks.length)
			if(commandPacks.length>0)
			{
			dispatcher.dispatchEvent(new DataStoreCommandPackEvent(DataStoreCommandPackEvent.SEND_TO_DATA_STORE,commandPacks));
			locked = true;
			}
		}
			
			
		
		
		override public function resetAllManaged():void
		{
			for each(var bm:IBazManaged in lockedObjects)
			{
				bm.reset();
			}
		}		

	}
}